
clear all
set more off

/* Inputs */ 

local in_firms        "/data2/cedsei/firm/not_firm_pop.dta"
// From A1_definepop
foreach num of numlist 1985(1)2018 {
	local in_jobb_`num' "/data/rawdata/cleaned/jobb_`num'"
}

/* Outputs */ 

local out_interm	"/data2/cedsei/firm/temp_rams.dta"
local out_rams  	"/data2/cedsei/firm/rams_ourpop.dta"

********************************************************************************

local rams = 1 
if `rams'==1 {
tempfile a0 
foreach num of numlist 1985(1)2018 {
	di "Year: `num'"
	qui {
	clear
	use lopnr lopnr_peorgnr lopnr_cfarnr agkat astlan astsni* lonfink manfran mantill year using `in_jobb_`num''
	destring astlan, replace 
	destring astsni*, replace
	merge m:1 lopnr_peorgnr using "`in_firms'"
	keep if _merge==3 
	
	gcollapse (min) manfran (max) mantill lopnr_cfarnr astlan astsni* (sum) lonfink, by(lopnr lopnr_peorgnr agkat)	
	bys lopnr_peorgnr lopnr_cfarnr: gen first=_n==1
	egen nrofast = total(first), by(lopnr_peorgnr)
	gen year = `num'
	if `num'>1985 {
		append using `out_interm'
	}
	save `out_interm', replace 
	}
}

clear 
use  `out_interm' 
gen tenure = mantill - manfran + 1 
bys lopnr_peorgnr lopnr (year): gen cumten = sum(tenure)

hashsort lopnr_peorgnr lopnr year -lopnr_cfarnr
by lopnr_peorgnr lopnr year: keep if _n==1
save "`out_rams'", replace
}
